import pymysql
from code.util.db import sqlite_util as sqlite_db
from code.tools import doc_writer as dw


def select_field(table_name_entry):
    # 查询py自己的sqlite
    res_list = sqlite_db.select("select * from tb_info")
    res = res_list[0]

    # 连接到 MySQL 数据库
    connection = pymysql.connect(
        host = res[1],  # 替换为你的主机地址
        user = res[2],  # 替换为你的用户名
        password = res[3],  # 替换为你的密码
        database = res[4],  # 替换为你的数据库名
        charset='utf8mb4',  # 使用适当的编码
    )

    try:
        # 创建游标对象
        with connection.cursor() as cursor:
            # 执行 SQL 查询，获取表字段信息
            # 查询 activation_record 表的字段信息
            table_name = table_name_entry.get()
            query = f"""
               SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_SCHEMA = '{res[4]}' AND TABLE_NAME = '{table_name}';
               """
            cursor.execute(query)
            # results = cursor.fetchall()
            # print(results)

            # 遍历结果
            print(f"{'Field':<20}{'Type':<20}{'COLUMN_COMMENT':<20}")
            print("-" * 40)
            # res = cursor.fetchall();
            # return res
            table_info_list = []
            for row in cursor.fetchall():
                field_name, data_type, column_comment = row[0], row[1], row[2]
                print(f"{field_name:<20}{data_type:<20}{column_comment:<20}")
                table_info_list.append(row)
            dw.write_doc(table_info_list)
    finally:
        # 关闭数据库连接
        print("关闭连接...")
        connection.close()


